/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'package:qt_embedded_flutter_page/src/messages.g.dart';

import 'src/engineIdManager.dart';

void main(List<String> args) {
  String engineId = args.isNotEmpty ? args[0] : 'default_engine_id';
  print('当前引擎id:' + engineId);
  EngineIdManager().setEngineId(engineId);
  WidgetsFlutterBinding.ensureInitialized();
  FlutterChannel.setup(FlutterChannelImp());
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/p1': (context) => P1Screen(),
      },
    );
  }
}

class FlutterChannelImp implements FlutterChannel {
  @override
  void nativeCallFlutter(N2FMessage msg) {
    // TODO: implement nativeCallFlutter
    print('收到native发过来的消息' + (msg.msg ?? '123'));
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 获取当前时间
    DateTime now = DateTime.now();

    // 格式化日期时间部分
    String formattedDate =
        '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
        '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}'
        '.${now.millisecond.toString().padLeft(3, '0')}';
    print("首页已启动，当前时间 $formattedDate");
    return Scaffold(
      appBar: AppBar(
        title: Text('主界面'),
      ),
      body: Center(
        child: Column(children: [
          ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/p1');
            },
            child: Text('P1 TEST'),
          ),
        ]),
      ),
    );
  }
}

class P1Screen extends StatefulWidget {
  const P1Screen({Key? key}) : super(key: key);

  @override
  State<P1Screen> createState() => _P1ScreenState();
}

class _P1ScreenState extends State<P1Screen> implements FlutterChannel {
// 创建一个 TextEditingController 来管理 TextField 的值。
  final TextEditingController _controller = TextEditingController();
  final TextEditingController _controllerSecond = TextEditingController();
  late NativeChannel _nativeChannel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._nativeChannel = NativeChannel();
    FlutterChannel.setup(this);
  }

  @override
  void nativeCallFlutter(N2FMessage msg) {
    // TODO: implement nativeCallFlutter
    print('22收到native发过来的消息' + (msg.msg ?? '123'));
    setState(() {
      this._controllerSecond.text = msg.msg ?? "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('P1 验收测试'),
      ),
      body: Column(
        children: <Widget>[
          // 页面顶部的固定内容
          Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(children: <Widget>[
                Row(children: <Widget>[
                  Text(
                    'flutter--->桥接层--->QT：',
                    style: TextStyle(fontSize: 14),
                  ),
                  Expanded(
                    child: TextField(
                      controller: this._controller,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: '',
                      ),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      print('发送文本：123' + this._controller.text);
                      this._nativeChannel.flutterCallNative(
                          F2NMessage.decode([this._controller.text]));
                    },
                    child: Text('发送'),
                  ),
                ]),
                Row(children: <Widget>[
                  ElevatedButton(
                    onPressed: () {
                      print('单击：123');
                    },
                    child: Text('单击'),
                  ),
                  GestureDetector(
                    onDoubleTap: () {
                      print('双击：123');
                    },
                    child: ElevatedButton(
                      onPressed: () {}, //事件都被GestureDetector拦截，不用管
                      child: Text('双击'),
                    ),
                  ),
                  GestureDetector(
                    onSecondaryTap: () {
                      print('右键：123');
                    },
                    child: ElevatedButton(
                      onPressed: () {},
                      child: Text('右键'),
                    ),
                  ),
                ]),
                Row(children: <Widget>[
                  Text(
                    'QT--->桥接层--->flutter：',
                    style: TextStyle(fontSize: 14),
                  ),
                  Expanded(
                    child: TextField(
                      controller: this._controllerSecond,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: '',
                      ),
                    ),
                  ),
                ]),
              ])),
          // 可滚动的部分
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  // 添加多个 Text 组件来模拟大量内容
                  for (int i = 0; i < 20; i++)
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      child: Text(
                        'This is scrollable content line number $i',
                        style: TextStyle(fontSize: 20),
                      ),
                    ),
                ],
              ),
            ),
          ),
          // 页面底部的固定内容（可选）
        ],
      ),
    );
  }
}
